package com.fita.admin.web.controller.authority;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.page.Page;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.utils.CollectionUtils;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.resolver.Preloading;
import com.demo2do.core.web.utils.WebUtils;
import com.fita.admin.entity.search.principal.PrincipalSearch;
import com.fita.admin.entity.security.Login;
import com.fita.admin.service.DataService;
import com.fita.admin.service.authority.PrincipalService;
import com.fita.admin.service.authority.RoleService;
import com.fita.admin.web.resolver.Secure;
import com.fita.entity.authority.Role;
import com.fita.entity.principal.District;
import com.fita.entity.principal.Principal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 用户管理
 *
 * @author cuteHU
 *
 */
@Controller
@RequestMapping("/principals")
@MenuSetting("menu-authority")
public class PrincipalController {

    private Logger logger = LoggerFactory.getLogger(PrincipalController.class);

    @Autowired
    private PrincipalService principalService;

    @Autowired
    @Qualifier("dataService")
    private DataService<District> districtService;

    @Autowired
    private RoleService roleService;

    /**
     * @param login
     * @param page
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    @MenuSetting("submenu-principal-management")
    public ModelAndView list(@Secure Login login, Page page) {

        ModelAndView modelAndView = new ModelAndView("authority/principal/principal-list");

        int totals = principalService.count(login);
        if (totals > 0) {
            List<Principal> principals = principalService.list(login, page.with(totals));
            List<Role> roles = roleService.listAll(Role.class);
            Map<String, Role> roleMaps = CollectionUtils.constructMapValue(roles, "code");
            modelAndView.addObject("roles", roleMaps);
            modelAndView.addObject("principals", principals);
            modelAndView.addObject("page", page);

        }
        return modelAndView;

    }

    /**
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.GET)
    public String search() {
        return "authority/principal/principal-search";
    }

    /**
     * @param search
     * @param page
     * @param request
     * @return
     */
    @MenuSetting("submenu-principal-management")
    @RequestMapping(value = "", method = RequestMethod.GET, params = "filter")
    public ModelAndView onSearch(PrincipalSearch search, Page page, HttpServletRequest request) {

        ModelAndView modelAndView = new ModelAndView("authority/principal/principal-list");

        int totals = principalService.countSearch(Principal.class, search.getPreparedFilter(false));
        if (totals > 0) {

            List<Principal> principals = principalService.search(Principal.class, search, page.with(totals));
            List<Role> roles = roleService.listAll(Role.class);
            Map<String, Role> roleMaps = CollectionUtils.constructMapValue(roles, "code");
            modelAndView.addObject("roles", roleMaps);
            modelAndView.addObject("principals", principals);
            modelAndView.addObject("page", page);
            modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "filter", "page"));

        }

        return modelAndView;

    }

    /**
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    @MenuSetting("submenu-principal-management")
    public ModelAndView create() {
        ModelAndView modelAndView = new ModelAndView("authority/principal/principal-create");
        return modelAndView;
    }

    /**
     * @param principal
     * @param districtId
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onCreate(Principal principal,
            @RequestParam(name = "districtId", required = false) Long districtId) {

        HttpResult httpResult = new HttpResult();
        District district = null;

        try {

            if (districtId != null) {
                district = districtService.load(District.class, districtId);
                principalService.createPrincipal(principal, district);
                httpResult.success().message("新增用户成功");
            } else {
                principalService.save(principal);
                httpResult.success().message("新增用户成功");
            }

        } catch (BusinessException e) {
            httpResult.fail(e.getCode()).message(e.getMessage());
            logger.error("onCreate occurs error: ", e);

        } catch (Exception e) {
            logger.error("onCreate occurs error: ", e);
            httpResult.fail("500").message("新增用户失败");
        }

        return httpResult;
    }

    /**
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/edit", method = RequestMethod.GET)
    public ModelAndView edit(@PathVariable("id") Long id) {

        ModelAndView modelAndView = new ModelAndView("authority/principal/principal-edit");

        Principal principal = principalService.load(Principal.class, id);
        modelAndView.addObject("principal", principal);

        return modelAndView;
    }

    /**
     * @param id
     * @param principal
     * @param districtId
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onEdit(@Preloading("principalId") Principal principal,
            @RequestParam(name = "districtId", required = false) Long districtId) {

        HttpResult httpResult = new HttpResult();
        District district = null;
        try {

            if (districtId != null) {
                district = districtService.load(District.class, districtId);
                principalService.updatePrincipal(principal, district);
                httpResult.success().message("修改用户信息成功");
            } else {
                principalService.update(principal);
                httpResult.success().message("修改用户信息成功");
            }

        } catch (Exception e) {
            httpResult.fail("500").message("修改用户信息失败");
            logger.error("#onEdit() - edit fail, exception is [{}]", e);
        }

        return httpResult;
    }

    /**
     * display reset password panel
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/reset-password", method = RequestMethod.GET)
    public ModelAndView resetPassword(@PathVariable Long id) {
        ModelAndView modelAndView = new ModelAndView("authority/principal/principal-reset-password");
        modelAndView.addObject("id", id);
        return modelAndView;
    }

    /**
     * reset password
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/reset-password", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onResetPassword(@PathVariable("id") Long id) {
        HttpResult result = new HttpResult();
        try {

            Principal principal = principalService.load(Principal.class, id);

            principalService.resetPassword(principal);

            result.success().message("重置密码成功！");

        } catch (Exception e) {

            result.fail("500").message("重置密码失败！");
        }

        return result;
    }

    /**
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/freeze", method = RequestMethod.GET)
    public ModelAndView freeze(@PathVariable Long id) {
        ModelAndView modelAndView = new ModelAndView("authority/principal/principal-freeze");
        modelAndView.addObject("id", id);
        return modelAndView;
    }

    /**
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/freeze", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onFreeze(@PathVariable("id") Long id) {
        HttpResult result = new HttpResult();
        try {

            Principal principal = principalService.load(Principal.class, id);

            principalService.freeze(principal);

            result.success().message("冻结成功！");

        } catch (Exception e) {

            result.fail("500").message("冻结失败！");
        }

        return result;
    }

    /**
     * @param id
     * @return
     */

    @RequestMapping(value = "/{id}/activate", method = RequestMethod.GET)
    public ModelAndView activate(@PathVariable Long id) {
        ModelAndView modelAndView = new ModelAndView("authority/principal/principal-activate");
        modelAndView.addObject("id", id);
        return modelAndView;
    }

    /**
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/activate", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onActivate(@PathVariable("id") Long id) {
        HttpResult result = new HttpResult();
        try {

            Principal principal = principalService.load(Principal.class, id);

            principalService.activate(principal);

            result.success().message("激活成功！");

        } catch (Exception e) {

            result.fail("500").message("激活失败！");
        }
        return result;
    }
}
